<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getPage">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="80">
			</el-table-column>
			<el-table-column prop="sn" label="编号" width="140" sortable>
			</el-table-column>
			<el-table-column prop="name" label="姓名" width="140" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="200" sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state == 0">正常</span>
					<span style="color: red" v-else-if="scope.row.state == -1">禁用</span>
					<span style="color: gold" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="200" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="父部门" width="200" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="page"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--
			新增或编辑界面
			:rules：声明校验规则
			ref：绑定当前表单，并给它取一个别名
		-->
		<el-dialog title="新增/编辑" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
			<el-form :model="departmentForm" label-width="80px" :rules="departmentFormRules" ref="departmentForm">

				<el-form-item label="名称" prop="name">
					<el-input v-model="departmentForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="编码" prop="sn">
					<el-input v-model="departmentForm.sn" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="状态">
					<el-radio-group v-model="departmentForm.state">
						<el-radio class="radio" :label="0">正常</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="管理员" prop="manager">
					<!--<el-input v-model="departmentForm.manager" auto-complete="off"></el-input>-->
					<!--
						v-for：遍历员工的集合，得到每一个对象
						:key：选中每个对象的id
						:label：选中后，窗体显示的值
						:value：最终绑定给model层的数据，通过这个属性把数据传到后台（如果是一个对象，需要使用value-key这个属性绑定）
						value-key="id"这个属性先找到:key这个主键id,在通过id找到:value="item"这个具体的对象
					-->
					<el-select v-model="departmentForm.manager" value-key="id" placeholder="请选择">
						<el-option
								v-for="item in employees"
								:key="item.id"
								:label="item.username"
								:value="item">
							<span style="float: left">{{ item.username }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="父部门" prop="parent">
					<!--<el-input v-model="departmentForm.parent" auto-complete="off"></el-input>-->
					<!--<el-input v-model="departmentForm.parent" auto-complete="off"></el-input>-->
					<!--
						:options：双向绑定data层数据
						value：选定后传递给后端的值
						label：选中后显示到窗体的值
					-->
					<el-cascader v-model="departmentForm.parent"
								 :options="deptTree"
								 :props="{
								checkStrictly: true,
								value: 'id',
								label: 'name'
							}"
								 clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="departmentFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="departmentLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>

	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
				departments: [],
				total: 0,
				page: 1,
				pageSize: 10,
				listLoading: false,
				sels: [],//列表选中行

				departmentFormVisible: false, //新增或编辑界面是否显示
				departmentLoading: false,	// 忙等框是否显示
				departmentFormRules: {		// 声明校验规则
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
                    sn: [
                        { required: true, message: '请输入编号', trigger: 'blur' }
                    ]
				},
				//编辑界面数据
				departmentForm: {
					id: null,
					name: '',
					sn: '',
					state: 0,
					manager: null,
					parent: null
				},
				employees:[],
                deptTree:[]
			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getDepartments();
			},
            // 高级查询每次定位到第一页
            getPage(){
                this.page = 1;
                this.getDepartments();
            },
			//获取部门列表
			getDepartments() {
				let para = {
					currentPage: this.page,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword
				};
				this.listLoading = true;	// 开启忙等框
				// 发送axios请求，从后端拿数据
				this.$http.post("/department",para)
					.then(result=>{
                        this.total = result.data.total;
                        this.departments = result.data.rows;
                        this.listLoading = false;
					})
					.catch(result=>{
                        this.$message({
                            message: '系统异常',
                            type: 'error'
                        });
					})
				//NProgress.start();
				/*getDepartmentListPage(para).then((res) => {
					this.total = res.data.total;
					this.departments = res.data.departments;
					this.listLoading = false;
					//NProgress.done();
				});*/
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '温馨提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true; // 开启忙等框
					//NProgress.start();
					this.$http.delete("/department/"+row.id) // row.id拿到当前部门的id，传到后台去
						.then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page = 1; // 如果删除成功，跳转到第一页
							}else {
                                this.$message({
                                    message: '删除失败'+result.data.message,
                                    type: 'error'
                                });
							}
                            this.getDepartments(); // 重新刷新列表
						})
						.catch(result=>{

						})
					/*removeDepartment(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDepartments();
					});*/
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.departmentFormVisible = true;	// 显示编辑弹出框
				this.departmentForm = Object.assign({}, row);	// 回显数据 ，克隆当前行的数据
                this.getDeptTree(); // 点击新增触发函数，去后台查询部门树
                // 回显父部门
                let dirPath = row.dirPath; // /2/5/11
                if(dirPath){
                    let tmp = [];
                    if(dirPath){
                        let dirPaths =  dirPath.trim().split("/"); // ['','2','5','11']
                        // console.log(dirPaths)
                        for(let i=1;i<dirPaths.length-1;i++){
                            tmp[i-1] = parseInt(dirPaths[i]);
                        }
                    }
                    this.departmentForm.parent = tmp; //根据dirpath构造数组
                }
			},
			//显示新增界面
			handleAdd: function () {
				this.departmentFormVisible = true; // 显示新增弹出框
                this.departmentForm = { // 清空表单数据
                    id: null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager: null,
                    parent: null
                }
                this.getDeptTree(); // 点击新增触发函数，去后台查询部门树
			},
			//编辑
			save: function () {
				this.$refs.departmentForm.validate((valid) => { // 再一次触发表单校验
					if (valid) {
						this.$confirm('确认提交吗？', '温馨提示', {}).then(() => {
							this.departmentLoading = true;		// 显示忙等框
							//NProgress.start();
							let para = Object.assign({}, this.departmentForm);

                            // 因为这里得到的parent是一个数组，例如：[1,12]，后台parent又是一个对象，因此我们要转换
                            if(para.parent){	// 当父部门不为空的时候才转换
								if(para.parent.length == 0){ // 当部门本身有父部门，修改的时候不选择部门的时候，此时para.parent={}
									para.parent=null;
								}else {
                                    // 从表单中复制对象得到parent
                                    let paraArray = para.parent // [1,12]
                                    // 将parent数组中的最后一个值拿出来，最后一个值才是我们选中的父部门
                                    let lastParentId = paraArray[paraArray.length-1]
                                    // 重新给parent对象赋值，
                                    para.parent = {"id":lastParentId};
								}
                            }

							this.$http.put("/department",para)
								.then(result=>{
                                    this.departmentLoading = false;	// 关闭忙等框
									if (result.data.success){
                                        this.$message({
                                            message: "操作成功!",
                                            type: 'success'
                                        });
                                        this.departmentFormVisible = false;	// 关闭弹出框
                                        this.page = 1; 						// 定位到第一页
                                        this.getDepartments(); 				// 重新刷新列表
									}else {
                                        this.$message({
                                            message: result.data.message,	// 直接提示后端错误
                                            type: 'error'
                                        });
									}
								})
								.catch(result=>{
                                    this.$message({
                                        message: '系统错误',
                                        type: 'error'
                                    });
                                    this.departmentLoading = false;		// 关闭忙等框
                                    this.departmentFormVisible = false; // 关闭弹出框
								})

							/*departmentDepartment(para).then((res) => {
								this.departmentLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['departmentForm'].resetFields();
								this.departmentFormVisible = false;
								this.getDepartments();
							});*/
						});
					}
				});
			},

			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id); // [1,2,3]
				this.$confirm('确认删除选中记录吗？', '温馨提示', {
					type: 'warning'
				}).then(() => { // 返回框的确认框
					this.listLoading = true; // 开启忙等框
					//NProgress.start();
					// let para = { ids: ids };
					this.$http.patch("/department",ids)
						.then(result=>{
                            this.listLoading = false; // 关闭忙等框
							if (result.data.success){ // 删除成功
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
								this.page = 1; // 删除成功，定位到第一页
							}else {
                                this.$message({
                                    message: '删除失败'+result.message,
                                    type: 'error'
                                });
							}
                            this.getDepartments(); // 重新刷新列表
						})
						.catch(result=>{
                            this.listLoading = false; // 关闭忙等框
                            this.$message({
                                message: '系统异常',
                                type: 'error'
                            });
						})
					/*batchRemoveDepartment(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDepartments();
					});*/
				}).catch(() => {	// 返回框的取消框

				});
			},
            getEmployees(){
                this.$http.get("/employee")
                    .then(result=>{
                        if (result.data){
                            this.employees = result.data; // result.data 获取员工的集合
                        }
                    })
            },
            getDeptTree(){
                this.$http.get("/department/tree")
                    .then(result=>{
                        if (result.data){
                            this.deptTree = result.data; // result.data 获取部门树的集合
                        }
                    })
            }
		},
		mounted() {
			this.getDepartments();
            this.getEmployees();	// 页面加载就查询员工的所有数据
		}
	}

</script>

<style scoped>

</style>